const models = require('../db/mysqldb/index')
const sequelize = require('sequelize/index')
const Op = sequelize.Op
const { ErrorModel, SuccessModel, sonsTree } = require('../utils/index')
const logger = require('../utils/logger')
const _ = require('lodash')

/**
 * 菜单编辑时没加入过多的限制 目前还没考虑好菜单模块限制怎么加
 */
class SysMenuController {
  /**
   * @description 获取菜单
   * @param {*} user (role_id)
   */
  static async getMenu(req, res) {
    try {
      const { role_id } = req.user
      // 登陆者的role_id 查找菜单节点
      const menuNodeList = await models.sys_role_menu.findAll({
        where: {
          role_id
        },
        attributes: ['menu_id']
      })
      logger.info(`SysMenuController`, `getMenu`, `menuNodeList`, menuNodeList)
      if (!menuNodeList.length) {
        res.json(new SuccessModel([], `查询成功`))
        return
      }
      let menu_id_list = []
      menuNodeList.forEach(ele => {
        menu_id_list.push(ele.menu_id)
      })
      logger.info(`SysMenuController`, `getMenu`, `menu_id_list`, menu_id_list)
      // 根据菜单节点查询所有的菜单
      const menuList = await models.sys_menu.findAll({
        where: {
          type: '0',
          del_flag: '0',
          menu_id: {
            [Op.in]: menu_id_list
          }
        }
      })
      logger.info(`SysMenuController`, `getMenu`, `menuList`, menuList)
      const menuTree = sonsTree(menuList, -1, 'menu_id')
      logger.info(`SysMenuController`, `getMenu`, `menuTree`, menuTree)
      res.json(new SuccessModel(menuTree, `查询成功`))
    } catch (error) {
      logger.error(`SysMenuController`, `getMenu`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 获取按钮权限
   * @param {*} req.user
   */
  static async getPremission(req, res) {
    try {
      const { role_id } = req.user
      const menuNodeList = await models.sys_role_menu.findAll({
        where: {
          role_id
        },
        attributes: ['menu_id']
      })
      logger.info(
        `SysMenuController`,
        `getPremission`,
        `menuNodeList`,
        menuNodeList
      )
      if (!menuNodeList.length) {
        res.json(new SuccessModel([], `查询成功`))
        return
      }
      let menu_id_list = []
      menuNodeList.forEach(ele => {
        menu_id_list.push(ele.menu_id)
      })
      logger.info(
        `SysMenuController`,
        `getPremission`,
        `menu_id_list`,
        menu_id_list
      )
      const menuList = await models.sys_menu.findAll({
        where: {
          type: '1',
          del_flag: '0',
          menu_id: {
            [Op.in]: menu_id_list
          },
          permission: {
            [Op.not]: ''
          }
        },
        attributes: ['permission']
      })
      logger.info(`SysMenuController`, `getPremission`, `menuList`, menuList)
      const btnPermissionArr = menuList.map(item => {
        return item.permission
      })
      logger.info(
        `SysMenuController`,
        `getPremission`,
        `btnPermissionArr`,
        btnPermissionArr
      )
      res.json(new SuccessModel(btnPermissionArr, `查询成功`))
    } catch (error) {
      logger.error(`SysMenuController`, `getPremission`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 新增菜单
   * @param {*} name
   * @param {*} permission
   * @param {*} path
   * @param {*} url
   * @param {*} method
   * @param {*} parent_id
   * @param {*} icon
   * @param {*} component
   * @param {*} sort
   * @param {*} type
   */
  static async addMenu(req, res) {
    try {
      const {
        name,
        permission,
        path,
        url,
        method,
        parent_id = -1,
        icon,
        component,
        sort = 1,
        type
      } = req.body
      logger.info(`SysMenuController`, `addMenu`, `req.body`, req.body)
      if (!name || !type) {
        res.json(new ErrorModel(`缺少必填项`))
        return
      }
      const menuInfo = await models.sys_menu.create({
        name,
        permission,
        path,
        url,
        method,
        parent_id,
        icon,
        component,
        sort,
        type
      })
      logger.info(`SysMenuController`, `addMenu`, `menuInfo`, menuInfo)
      res.json(new SuccessModel(`新增成功`))
    } catch (error) {
      logger.error(`SysMenuController`, `addMenu`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 更新菜单
   * @param {*} menu_id
   * @param {*} name
   * @param {*} permission
   * @param {*} path
   * @param {*} url
   * @param {*} method
   * @param {*} parent_id
   * @param {*} icon
   * @param {*} component
   * @param {*} sort
   * @param {*} type
   */
  static async editMenu(req, res) {
    try {
      const {
        menu_id,
        name,
        permission,
        path,
        url,
        method,
        parent_id,
        icon,
        component,
        sort = 1,
        type
      } = req.body
      logger.info(`SysMenuController`, `editMenu`, `req.body`, req.body)
      if (!menu_id || !name || !type || !parent_id) {
        res.json(new ErrorModel(`缺少必填项`))
        return
      }
      // 根据menu_id更新数据
      const menuInfo = await models.sys_menu.update(
        {
          name,
          permission,
          path,
          url,
          method,
          parent_id,
          icon,
          component,
          sort,
          type,
          update_date_timestamp: Date.now()
        },
        {
          where: {
            menu_id
          }
        }
      )
      logger.info(`SysMenuController`, `editMenu`, `menuInfo`, menuInfo)
      res.json(new SuccessModel(`更新成功`))
    } catch (error) {
      logger.error(`SysMenuController`, `editMenu`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除菜单
   * @param {*} menu_id
   */
  static async delMenu(req, res, next) {
    const { menu_id } = req.body
    logger.info(`SysMenuController`, `delMenu`, `req.body`, req.body)
    try {
      // 判断菜单id是否存在
      if (!menu_id) {
        res.json(new ErrorModel('缺少必填项'))
        return
      }
      // del_flag = 1 软删除
      const menu_del_info = await models.sys_menu.update({del_flag:'1'},{
        where: {
          menu_id,
          update_date_timestamp: Date.now()
        }
      })
      logger.info(
        `SysMenuController`,
        `delMenu`,
        `menu_del_info`,
        menu_del_info
      )
      res.json(new SuccessModel([], '删除成功'))
    } catch (error) {
      logger.error(`SysMenuController`, `delMenu`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
}

module.exports = {
  SysMenuController
}
